<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
	/**
	 * 关联到模型的数据表
	 *
	 * @var string
	 */
	protected $table = 'dqm_book';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = [
		'book_title'
	];

	const FIELD_BOOK_ID = 'book_id';
	const FIELD_USER_ID = 'user_id';
	const FIELD_BOOK_TITLE = 'book_title';

	/**
	 * 获取当前用户下的所有笔记本列表
	 *
	 * @param $user_id
	 * @return null
	 */
	static public function get_books_by_user_id($user_id, $search_book = ''){
		if(!empty($user_id)){
			$condition['where'] = array(self::FIELD_USER_ID=>$user_id);
			$select['fields'] = array('book_id', 'book_title', 'created_time', 'updated_time');
			$result = Book::select($select['fields'])->where($condition['where'])->where(self::FIELD_BOOK_TITLE, 'LIKE', '%'.$search_book.'%')->get();
			return $result;
		}
		return null;
	}

	/**
	 * @param $user_id
	 * @param $book_title
	 * @return bool
	 */
	static function get_book_by_user_id_and_book_title($user_id, $book_title){
		$condition['where'] = array(self::FIELD_USER_ID=>$user_id, self::FIELD_BOOK_TITLE=>$book_title);
		$result = Book::where($condition['where'])->first();
		if(empty($result)){
			return false;
		}else{
			return true;
		}
	}

	/**
	 * @param array $data
	 * @return bool|null
	 */
	static public function add($data = array()){
		if(!empty($data)){
			$now = time();
			if(!isset($data['created_time'])){
				$data['created_time'] = $now;
			}
			if(!isset($data['updated_time'])) {
				$data['updated_time'] = $now;
			}
			$book_id = Book::insertGetId($data);
			if($book_id){
				return true;
			}else{
				return false;
			}
		}
		return null;
	}
}
